
import React, { useState, useEffect, useRef } from "react";
import { Button, Form, Input, Table, Pagination, Popconfirm, Typography, DatePicker, Upload } from 'antd';
import { SearchOutlined, ReloadOutlined, CloudUploadOutlined, DownloadOutlined } from '@ant-design/icons';
import type { TableColumnsType, PaginationProps, UploadProps } from 'antd';
import Common from "@/components/common/index"
import { getOrders, deleteById, updateById } from "@/common/api"



const { RangePicker } = DatePicker;
const Order: React.FC = () => {
    useEffect(() => {
        getData(); // 页面加载时自动调用一次
    }, []);
    const [loadings, setLoadings] = useState<boolean>(false);
    const [tableData, setTableData] = useState<any[]>([]);

    const startTime = useRef('');
    const endTime = useRef('');

    const [form2] = Form.useForm();
    const onFinish = (values: any) => {
        startTime.current = values.applyTime ? values.applyTime[0].format('YYYY-MM-DD HH:mm:ss') : ''
        endTime.current = values.applyTime ? values.applyTime[1].format('YYYY-MM-DD HH:mm:ss') : ''
        pageNumRef.current = 1;
        setCurrent(1)
        getData()
    };
    const getData = () => {
        const values = form2.getFieldsValue();
        delete values.applyTime
        let param = {
            ...values,
            startTime: startTime.current,
            endTime: endTime.current,
            pageSize: pageSizeRef.current,
            pageNum: pageNumRef.current
        }
        setLoadings(true)
        getOrders(param).then((res: any) => {
            setLoadings(false)
            if (res.success) {
                setTableData(res.data.records)
                total.current = res.data.total
            } else {

            }
        })
    }

    const props: UploadProps = {
        name: 'file',
        action: () => {
            if (process.env.NODE_ENV == "development") {
                return "http://192.168.10.87:8611/api/orderGoods/import";
            } else {
                const host = window.location.protocol + "//" + window.location.host;
                return `${host}/api/orderGoods/import`;
            }
        },
        headers: {},
        onChange(info) {
            if (info.file.status !== 'uploading') {
            }
            if (info.file.status === 'done') {
                if (info.file.response.success) {
                    $message.success(info.file.response.message);
                } else {
                    $message.error(info.file.response.message);
                }
            } else if (info.file.status === 'error') {
                $message.error('导入失败');
            }
        },
    };
    const download = () => {
        if (process.env.NODE_ENV == "development") {
            window.location.href = `http://192.168.10.87:8611/api/orderGoods/template`;
        } else {
            const host = window.location.protocol + "//" + window.location.host;
            window.location.href = `${host}/api/orderGoods/template`;
        }
    }


    const getTop = () => {
        return <Form
            layout="inline"
            form={form2}
            onFinish={onFinish}
            autoComplete="off"
        >
            <Form.Item name="orderCode" label="订单编号:" style={{ marginBottom: '10px' }}>
                <Input placeholder="请输入订单编号" />
            </Form.Item>
            <Form.Item name="applyTime" label="申请时间:" style={{ marginBottom: '10px' }}>
                <RangePicker showTime />
            </Form.Item>
            <Form.Item name="acceptUnit" label="接收单位:">
                <Input placeholder="请输入接收单位" />
            </Form.Item>
            <Form.Item style={{ marginBottom: '10px' }}>
                <Button icon={<SearchOutlined />} type="primary" htmlType="submit" loading={loadings}>查询</Button>
            </Form.Item>
            <Form.Item style={{ marginBottom: '10px' }}>
                <Button icon={<ReloadOutlined />} onClick={() => {
                    form2.resetFields();
                }} loading={loadings}>重置</Button>
            </Form.Item>
            <Form.Item style={{ marginBottom: '10px' }}>
                <Upload {...props}>
                    <Button icon={<CloudUploadOutlined />} type="primary">导入</Button>
                </Upload>
            </Form.Item>
            <Form.Item style={{ marginBottom: '10px' }}>
                <Button icon={<DownloadOutlined />} type="primary" onClick={download}>导入模板下载</Button>
            </Form.Item>

        </Form>
    }


    interface EditableCellProps extends React.HTMLAttributes<HTMLElement> {
        editing: boolean;
        dataIndex: string;
        title: any;
        inputType: 'number' | 'text';
        record: any;
        index: number;
    }
    const EditableCell: React.FC<React.PropsWithChildren<EditableCellProps>> = ({
        editing,
        dataIndex,
        title,
        inputType,
        record,
        index,
        children,
        ...restProps
    }) => {
        const inputNode = <Input />;
        return (
            <td {...restProps}>
                {editing ? (
                    <Form.Item
                        name={dataIndex}
                        style={{ margin: 0 }}
                        rules={[
                            {
                                required: false,
                                message: `请输入 ${title}!`,
                            },
                        ]}
                    >
                        {inputNode}
                    </Form.Item>
                ) : (
                    children
                )}
            </td>
        );
    };
    const [form] = Form.useForm();
    const [editingKey, setEditingKey] = useState('');
    const isEditing = (record: any) => record.id === editingKey;
    const edit = (record: any) => {
        form.setFieldsValue(record)
        setEditingKey(record.id);
    };

    const cancel = () => {   //取消编辑
        setEditingKey('');
    };
    const save = async (record: any) => {
        try {
            const row = await form.validateFields();
            updateById({ id: record.id, ...row }).then((res: any) => {
                if (res.success) {
                    $message.success('修改成功');
                    setEditingKey('');
                    getData()
                } else {
                    $message.error(res.message);
                }
            })
        } catch (errInfo) {
            console.log('验证失败:', errInfo);
        }
    };
    const handleDelete = (record: any) => {
        deleteById({ ids: record.id }).then((res: any) => {
            if (res.success) {
                $message.success('删除成功');
                getData()
            } else {
                $message.error(res.message);
            }
        })
    }

    const getCell = (record: any, title: any, dataIndex: any) => {
        return {
            record,
            dataIndex: dataIndex,
            title: title,
            inputType: 'text',
            editing: isEditing(record),
        }
    }

    const columns: TableColumnsType = [
        {
            title: '序号',
            dataIndex: 'index',
            width: 60,
            align: 'center' as const,
            render: (_text, _record, index) =>
                (pageNumRef.current - 1) * pageSizeRef.current + index + 1,
        },
        {
            title: '订单编号',
            dataIndex: 'orderCode',
            // width: 100,
            onCell: (record) => (getCell(record, '订单编号', 'orderCode')),
        },
        {
            title: '申请时间',
            dataIndex: 'applyTime',
            // width: 200,
            onCell: (record) => (getCell(record, '申请时间', 'applyTime')),
        },
        {
            title: '申请单位',
            dataIndex: 'applyUnit',
            // width: 180,
            onCell: (record) => (getCell(record, '申请单位', 'applyUnit'))
        },
        {
            title: '接收单位',
            dataIndex: 'acceptUnit',
            // width: 180,
            onCell: (record) => (getCell(record, '接收单位', 'acceptUnit'))
        },
        {
            title: '二级库',
            dataIndex: 'twoRank',
            //  width: 180,
            onCell: (record) => (getCell(record, '二级库', 'twoRank'))
        },
        {
            title: '地区',
            dataIndex: 'region',
            // width: 180,
            onCell: (record) => (getCell(record, '地区', 'region'))
        },
        {
            title: '订单类别',
            dataIndex: 'orderSort',
            width: 150,
            onCell: (record) => (getCell(record, '订单类别', 'orderSort'))
        },
        {
            title: '订单类型',
            dataIndex: 'orderType',
            width: 150,
            onCell: (record) => (getCell(record, '订单类型', 'orderType'))
        },
        {
            title: '状态',
            dataIndex: 'orderState',
            //  width: 180,
            onCell: (record) => (getCell(record, '状态', 'orderState'))
        },
        {
            title: '正反标识',
            dataIndex: 'goodsFlag',
            width: 150,
            onCell: (record) => (getCell(record, '正反标识', 'goodsFlag'))
        },
        {
            title: '设备分类',
            dataIndex: 'facilityKind',
            width: 180,
            onCell: (record) => (getCell(record, '设备分类', 'facilityKind'))
        },
        {
            title: '设备码',
            dataIndex: 'facilityCode',
            //  width: 180,
            onCell: (record) => (getCell(record, '设备码', 'facilityCode'))
        },
        {
            title: '设备码描述',
            dataIndex: 'codeDescribe',
            //  width: 240,
            onCell: (record) => (getCell(record, '设备码描述', 'codeDescribe'))
        },
        {
            title: '计划数量',
            dataIndex: 'planNum',
            width: 150,
            onCell: (record) => (getCell(record, '计划数量', 'planNum'))
        },
        {
            title: '实际数量',
            dataIndex: 'realNum',
            width: 150,
            onCell: (record) => (getCell(record, '实际数量', 'realNum'))
        },
        {
            title: '发车时间',
            dataIndex: 'departTime',
            width: 180,
            onCell: (record) => (getCell(record, '发车时间', 'departTime'))
        },
        {
            title: '操作',
            dataIndex: 'operation',
            fixed: 'right',
            render: (_: any, record) => {
                const editable = isEditing(record);
                return editable ? (
                    <span>
                        <Typography.Link style={{ marginInlineEnd: 8 }} onClick={() => cancel()}>
                            取消
                        </Typography.Link>
                        <Popconfirm title="是否确认?" onConfirm={() => save(record)}>
                            <a>确认</a>
                        </Popconfirm>
                    </span>
                ) : (
                    <>
                        <Typography.Link onClick={() => edit(record)} style={{ marginRight: 16 }}>
                            编辑
                        </Typography.Link>

                        {/* 新增的删除按钮 + Popconfirm 二次确认 */}
                        <Popconfirm
                            title="确定要删除这一行吗？"
                            okText="确认"
                            cancelText="取消"
                            onConfirm={() => handleDelete(record)}
                        >
                            <Typography.Link style={{ color: 'red' }}>删除</Typography.Link>
                        </Popconfirm>
                    </>
                );
            },
        },
    ];



    const getTable = () => {
        return <Form form={form} component={false}>
            <Table
                components={{
                    body: { cell: EditableCell },
                }}
                columns={columns}
                dataSource={tableData}
                scroll={{ x: 'max-content' }}
                pagination={false}
                sticky={true}
                style={{ height: '90%', overflowY: 'auto', overflowX: 'hidden' }}
                rowKey="id"
            /></Form>
    }
    const total = useRef(0);
    const pageNumRef = useRef(1);
    const pageSizeRef = useRef(10);
    const [current, setCurrent] = useState<number>(1);


    const onChange: PaginationProps['onChange'] = (page, pageSize) => {
        pageNumRef.current = page;
        pageSizeRef.current = pageSize;
        setCurrent(page)
        getData()
    }
    const getPagination = () => {
        return <Pagination

            size="small"
            total={total.current}
            showSizeChanger
            showQuickJumper
            showTotal={(total) => `共 ${total} 条`}
            onChange={onChange}
            current={current}
        />
    }


    return <>
        <Common top={getTop()} table={getTable()} paginations={getPagination()} />
    </>
}


export default Order